package com.soccernews.main;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlSerializer;



import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class News extends Activity  {
	ListView list;
	private List<Message> messages;
	private Object data = null;
	ProgressDialog pd;
	private int progressBarStatus = 0;
	private Handler progressBarHandler = new Handler();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading_screen);
        

    	
        new DownloadTask().execute();
        
    }
    private class DownloadTask extends AsyncTask<String, Void, Object> {
        protected Object doInBackground(String... args) {
            Log.i("MyApp", "Background thread starting");
            
            messages = loadFeed(ParserType.ANDROID_SAX);

            return messages;
        }

        protected void onPostExecute(Object result) {
            // Pass the result data back to the main activity
        	News.this.data = result;
        	setContentView(R.layout.news);
        	
        	list = (ListView)findViewById(R.id.message_list);
	 		list.setItemsCanFocus(false);
	 		list.setChoiceMode(ListView.PERSISTENT_ANIMATION_CACHE);
	 		list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	 		list.setAdapter(new MessageViewAdaptor(News.this, messages));
	    	 list.setOnItemClickListener(new OnItemClickListener() {
	    	 public void onItemClick(AdapterView<?> arg0, View view, int position, long index) {
	    		 
	    		 Intent mainIntent = new Intent(News.this, Details.class);
	    		 mainIntent.putExtra("param", messages.get(position).getLink().toString());
	    		 mainIntent.putExtra("param2", messages.get(position).getTitle());
	    		 News.this. startActivity(mainIntent);
	    		 
					
				 
	    		 
					
				}
	    	 });
            if (News.this.pd != null) {
            	News.this.pd.dismiss();
            }
        }

		
   }    

	private ArrayList loadFeed(ParserType type){
    	try{
    		Log.i("AndroidNews", "ParserType="+type.name());
	    	FeedParser parser = FeedParserFactory.getParser(type);
	    	long start = System.currentTimeMillis();
	    	messages = new ArrayList<Message>();
	    	messages = parser.parse();
	    	long duration = System.currentTimeMillis() - start;
	    	Log.i("AndroidNews", "Parser duration=" + duration);
	    	String xml = writeXml();
	    	Log.i("AndroidNews", xml);
	    	List<String> titles = new ArrayList<String>(messages.size());
	    	for (Message msg : messages){
	    		titles.add(msg.getTitle());
	    		
	    	}
	    	
	    	 
    	} catch (Throwable t){
    		Log.e("AndroidNews",t.getMessage(),t);
    	}
    	return (ArrayList) messages;
    }
	
	private String writeXml(){
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", "messages");
			serializer.attribute("", "number", String.valueOf(messages.size()));
			for (Message msg: messages){
				serializer.startTag("", "message");
				serializer.attribute("", "date", msg.getDate());
				serializer.startTag("", "title");
				serializer.text(msg.getTitle());
				serializer.endTag("", "title");
				serializer.startTag("", "url");
				serializer.text(msg.getLink().toExternalForm());
				serializer.endTag("", "url");
				serializer.startTag("", "body");
				serializer.text(msg.getDescription());
				serializer.endTag("", "body");
				serializer.endTag("", "message");
			}
			serializer.endTag("", "messages");
			serializer.endDocument();
			return writer.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
	}
	
	
}